// 调用百度tts接口，将文字转换为语音
import axios from 'axios';
import qs from 'qs';

const client_id = 'NgNMakklaRJeGRVX2Ay1Vv9H';
const client_secret = 'Ls7kZWD2iTkMP5oKI74h1ObEwa2O7N1r';
// 配音角色
const per = '5003'
// 语速
const spd = '6'
// 音调
const pit = '5'
// 音量
const vol = '15'
// 格式
const aue = '3'
// 语言
const lan = 'zh'
// 客户端类型
const ctp = '1'
//用户唯一标识
const cuid = 'GU41bGWtWZsm2M5HE2X6W9zymFMhvvld'
const token = '24.a4845a0ce0a1caba058542c63665e222.2592000.1724114653.282335-96952546';
//获取token
function getAccessToken() {
  return axios.get(`https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=' + ${client_id} + '&client_secret=' + ${client_secret}`, {
    params: {
      grant_type: 'client_credentials',
      client_id,
      client_secret
    }
  }).then(res => res.data.access_token)
}

//文字转语音
export async function speak(text: string) {
  // const token = await getAccessToken()
  const res = await axios.post('https://tsn.baidu.com/text2audio', qs.stringify({
    tex: text,
    tok: token,
    cuid,
    ctp,
    lan,
    aue,
    per,
    spd,
    pit,
    vol
  }), {
    headers: {
      'Accept':"*/*",
      'Content-Type': 'application/x-www-form-urlencoded'
    },
    responseType: 'blob'
  })
  //输出语音
  
  // 强制自动播放
  console.log(res.data);
  const url = window.URL.createObjectURL(res.data);
  const audio = new Audio(url);
  audio.play();
}